package com.aode.login.view.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.aode.common.bean.request.LoginData;
import com.aode.common.bean.web.Result;
import com.aode.login.R;
import com.aode.login.databinding.ActivityLoginBinding;
import com.aode.login.viewmodel.LoginViewModel;
import com.aode.utils.main.ToastUtils;

public class LoginActivity extends AppCompatActivity {
    private ActivityLoginBinding loginBinding;
    private LoginViewModel loginViewModel;
    private String name;
    private String password;
    private LoginData loginData;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loginBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        loginBinding.setLogin(LoginActivity.this);
        loginData = new LoginData();
        initListener();
    }

    private void initListener() {
        loginViewModel.getLogin().observe(this, result -> {
            if(result.getCode().equals("0")){
                if(result.getData()!=null){
                    ToastUtils.show(getApplicationContext(),"登录成功");
                }else{
                    ToastUtils.show(getApplicationContext(),"登录失败");
                }
            }else {
                ToastUtils.show(getApplicationContext(),result.getMsg());
            }
        });
    }

    private boolean checkLogin() {
        name = loginBinding.inputName.getText().toString().trim();
        password = loginBinding.inputPassword.getText().toString().trim();
        if(name.equals("")){
            ToastUtils.show(getApplicationContext(),"用户名不能为空");
            return false;
        }else if(password.equals("")){
            ToastUtils.show(getApplicationContext(),"密码不能为空");
            return false;
        }
        return true;
    }

    public void click(View view){
        if (view.getId() == R.id.buttonSignIn) {
            boolean a = checkLogin();
            login(a);
        }
    }

    private void login(boolean a) {
        if(a){
            loginViewModel.login(loginData);
        }
    }
}
